<?php

namespace app\common\model;

use think\Db;
use think\Model;
use app\common\model\user\GiftsMoneyLog;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo,$event_id = 0,$device_id = 0,$order_id = 0)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo,'event_id'=>$event_id,'device_id' => $device_id,'order_id'=>$order_id]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员赠送余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function gifts_money($money, $user_id, $memo,$event_id = 0,$device_id = 0,$order_id = 0)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->gifts_money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->gifts_money, $money, 2) : $user->gifts_money + $money;
                //更新会员信息
                $user->save(['gifts_money' => $after]);
                //写入日志
                GiftsMoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo,'event_id'=>$event_id,'device_id' => $device_id,'order_id'=>$order_id]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    // 递归计算代理分成
    public static function calculateCommission($totalCommission, $user_id)
    {
        $user = self::where('id', $user_id)->field('id,nickname,parent_id,parent_ids,divide_rate')->find();
        if($user['parent_ids']){
            $agent = explode(',',$user['parent_ids']);
            $allocations = [];
            $agentCommission = 0;
            foreach ($agent as $key => $agentId){
                $agentInfo = self::where('id', $agentId)->field('id,nickname,parent_id,parent_ids,divide_rate')->find();
                if($agentInfo['divide_rate'] < 1){
                    break;
                }else{
                    if($key == 0){
                        // 计算当前代理的分成
                        $agentCommission = $totalCommission * ($agentInfo['divide_rate']/100);
                    }else{
                        $agentCommission = $agentCommission - ($agentCommission * ($agentInfo['divide_rate']/100));
                    }
                    $allocations[] = [
                        'agent_id' => $agentInfo['id'],
                        'agent_name' => $agentInfo['nickname'],
                        'commission' => $agentCommission,
                    ];
                }
            }
            // 遍历数组，从后往前减去后续数组的commission值
            for ($i = count($allocations) - 1; $i >= 0; $i--) {
                // 初始化累计减去的commission为0
                $subtracted = 0;
                // 遍历所有后续的数组项（不包括当前项）
                for ($j = $i + 1; $j < count($allocations); $j++) {
                    $subtracted += $allocations[$j]['commission']; // 累加后续数组的commission值
                }
                // 更新当前数组的commission值
                $allocations[$i]['commission'] -= $subtracted;
            }
            return $allocations;
        }else{
            //如果分成比例小于1，则不分成
            if($user['divide_rate'] < 1){
                return [];
            }
            // 计算当前代理的分成
            $agentCommission = $totalCommission * ($user['divide_rate']/100);
            return [
                [
                    'agent_id' => $user_id,
                    'agent_name' => $user['nickname'],
                    'commission' => $agentCommission,
                ],
            ];
        }

    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }
}
